// 语音识别模块
const tencentAsr = require('./cloud/tencentAsr');
const logger = require('./logger');

// 创建录音管理器
const recorderManager = wx.getRecorderManager();

// 语音识别模块
const voiceRecognition = {
    // 录音状态
    isRecording: false,

    // 录音结果回调
    resolveFunction: null,
    rejectFunction: null,

    // 初始化
    init() {
        // 配置录音管理器事件
        this._setupRecorderEvents();

        // 初始化腾讯ASR
        this._initTencentAsr();

        logger.info('语音识别模块初始化完成');
    },

    // 配置录音管理器事件
    _setupRecorderEvents() {
        // 录音开始事件
        recorderManager.onStart(() => {
            logger.info('录音开始');
            this.isRecording = true;
        });

        // 录音结束事件
        recorderManager.onStop((res) => {
            logger.info('录音结束', { duration: res.duration, fileSize: res.fileSize });
            this.isRecording = false;

            // 如果有回调函数，则执行语音识别
            if (this.resolveFunction) {
                this._recognizeSpeech(res.tempFilePath);
            }
        });

        // 录音错误事件
        recorderManager.onError((err) => {
            logger.error('录音错误', err);
            this.isRecording = false;

            if (this.rejectFunction) {
                this.rejectFunction(err);
                this.resolveFunction = null;
                this.rejectFunction = null;
            }
        });
    },

    // 初始化腾讯ASR
    _initTencentAsr() {
        // 从本地存储获取API密钥
        const secretId = wx.getStorageSync('tencent_secretId') || '';
        const secretKey = wx.getStorageSync('tencent_secretKey') || '';

        // 初始化腾讯云ASR
        tencentAsr.init({
            secretId: secretId,
            secretKey: secretKey
        });
    },

    // 开始录音并识别
    recordAndRecognize(start = true, duration = 15000) {
        // 如果不是开始录音，则停止当前录音
        if (!start && this.isRecording) {
            recorderManager.stop();
            return new Promise((resolve, reject) => {
                this.resolveFunction = resolve;
                this.rejectFunction = reject;
            });
        }

        // 如果已经在录音，则直接返回
        if (this.isRecording) {
            return Promise.reject(new Error('已经在录音中'));
        }

        return new Promise((resolve, reject) => {
            this.resolveFunction = resolve;
            this.rejectFunction = reject;

            // 开始录音
            recorderManager.start({
                duration: duration,
                sampleRate: 16000,
                numberOfChannels: 1,
                encodeBitRate: 64000,
                format: 'mp3',
                frameSize: 50
            });
        });
    },

    // 停止录音
    stopRecording() {
        if (this.isRecording) {
            recorderManager.stop();
        }
    },

    // 识别语音
    _recognizeSpeech(tempFilePath) {
        wx.showLoading({
            title: '正在识别...',
        });

        // 调用腾讯云ASR识别
        tencentAsr.recognizeAndExtractKeyword(tempFilePath)
            .then(result => {
                wx.hideLoading();

                // 处理识别结果
                if (this.resolveFunction) {
                    logger.info('语音识别成功', {
                        text: result.text,
                        keyword: result.keyword
                    });

                    this.resolveFunction(result.keyword || result.text);
                    this.resolveFunction = null;
                    this.rejectFunction = null;
                }
            })
            .catch(err => {
                wx.hideLoading();
                logger.error('语音识别失败', err);

                if (this.rejectFunction) {
                    this.rejectFunction(err);
                    this.resolveFunction = null;
                    this.rejectFunction = null;
                }

                wx.showToast({
                    title: '识别失败，请重试',
                    icon: 'none'
                });
            });
    },

    // 测试API连接
    testConnection() {
        return tencentAsr.testConnection();
    },

    // 获取ASR服务日志
    getServiceLogs(maxLines = 100) {
        return tencentAsr.getServiceLogs(maxLines);
    }
};

module.exports = voiceRecognition; 